<?php

namespace App\Daos\Api\Login;

use App\Models\Users\Logs;
use App\Models\Users\Users;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class UserDao
{
    public static function slient ($openid,$session_key){
        $user = Users::where('openid',$openid)->first();
        if (!$user){
            $user = Users::insert([
                'openid' => $openid,
                'session_key' => $session_key,
                'created_at' => date('Y-m-d H:i:s'),
                'last_login' => date('Y-m-d H:i:s')
            ]);
            if (!$user){
                throw new \Exception('静默登录失败');
            }
            session(['slient_state' => 'first']);
        } else {
            Users::where('openid',$openid)->update([
                'session_key' => $session_key,
                'last_login' => date('Y-m-d H:i:s')
            ]);
            session(['slient_state' => 'other']);
        }
        return $user->id;
    }

    public static function mandate ($data){
        try {
            DB::beginTransaction();
            Users::where('id',$data['id'])->update([
                'icon' => $data['icon'],
                'nickname' => $data['nickname'],
                'last_login' => date('Y-m-d H:i:s')
            ]);
            Logs::insert([
                'uid' => $data['id'],
                'login_time' => date('Y-m-d H:i:s')
            ]);
            DB::commit();
            return true;
        } catch (\Exception $exception){
            DB::rollBack();
            return false;
        }
    }

    public static function mobile ($data){

        $user = Users::find($data['id']);
        if ($user->tel != $data['tel']){
            throw new \Exception('手机号错误，请重新尝试');
        }
        try {
            DB::beginTransaction();
            $user->last_login = date('Y-m-d H:i:s');
            $user->save();
            Logs::insert([
                'uid' => $data['id'],
                'login_time' => date('Y-m-d H:i:s')
            ]);
            DB::commit();
            return true;
        } catch (\Exception $exception){
            DB::rollBack();
            return false;
        }
    }
}
